import qs from 'qs';
import fetch from 'dva/fetch';
import { server } from 'configs';
import { Modal, message } from 'antd';

// 数据发送类型
const contentType = {
  'text': 'text/plain;charset=UTF-8',
  'json': 'application/json',
  'form': 'application/x-www-form-urlencoded;charset=UTF-8'
};
// 数据处理
const handleBody = (data, type) => {
  let tmpData = data;
  if (type === 'form') {
    tmpData = qs.stringify(tmpData);
  }
  return tmpData;
};

// 解析json
const parseJSON = response => response.json();
// 处理返回参数
const handleResponse = response => {
  if (response.status === 'ERROR') {
    Modal.error({
      title: response.msg || '请求失败'
    });
  }
  return response;
};

function checkStatus (response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  message.error('服务器内部错误');
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
const http = service => {
  const services = server.dev[service];
  return (url, params = {}, type = 'form') => {
    const options = {
      method: 'POST',
      // withCredentials:true,
      credentials: "include",
      // eslint-disable-next-line
      headers: new Headers({
        'Content-Type': contentType[type]
      }),
      body: handleBody(params, type)
    };
    return fetch(services + url, options)
      .then(checkStatus)
      .then(parseJSON)
      .then(handleResponse)
      .catch(err => ({ err }));
  };
};

export default http;
